export function detectSwipe(onSwipe, onSwipeEnd, options) {
  let initialPosition = null;

  function handleTouchStart(e) {
    initialPosition = {
      x: e.touches[0].clientX,
      y: e.touches[0].clientY
    };
    const info = {
      direction: {
        x: null,
        y: null
      },
      distance: {
        x: 0,
        y: 0
      },
      position: initialPosition
    };
    if (onSwipe) {
      onSwipe(options.useObjectParam ? info : null, info.distance, initialPosition);
    }
  }

  function handleTouchMove(e) {
    if (initialPosition === null) {
      return;
    }
    let currentPosition = {
      x: e.touches[0].clientX,
      y: e.touches[0].clientY
    };
    let diffX = initialPosition.x - currentPosition.x;
    let diffY = initialPosition.y - currentPosition.y;

    let direction = {
      x: null,
      y: null
    };
    direction.x = diffX > 0 ? "left" : "right";
    direction.y = diffY > 0 ? "up" : "down";
    let distance = {
      x: Math.abs(diffX),
      y: Math.abs(diffY)
    };

    const info = {
      direction,
      distance,
      position: currentPosition
    };
    if (onSwipe) {
      onSwipe(options.useObjectParam ? info : direction, distance, currentPosition);
    }
  }

  function handleTouchEnd(e) {
    if (initialPosition !== null) {
      let currentPosition = {
        x: e.changedTouches[0].clientX,
        y: e.changedTouches[0].clientY
      };
      let diffX = initialPosition.x - currentPosition.x;
      let diffY = initialPosition.y - currentPosition.y;

      let direction = {
        x: null,
        y: null
      };
      direction.x = diffX > 0 ? "left" : "right";
      direction.y = diffY > 0 ? "up" : "down";

      let distance = {
        x: Math.abs(diffX),
        y: Math.abs(diffY)
      };

      const info = {
        direction,
        distance,
        position: currentPosition
      };
      if (onSwipeEnd) {
        onSwipeEnd(options.useObjectParam ? info : direction, distance, currentPosition);
      }
      initialPosition = null;
    }
  }

  window.addEventListener("touchstart", handleTouchStart, false);
  window.addEventListener("touchmove", handleTouchMove, false);
  window.addEventListener("touchend", handleTouchEnd, false);

  return function removeSwipeListener() {
    window.removeEventListener("touchstart", handleTouchStart);
    window.removeEventListener("touchmove", handleTouchMove);
    window.removeEventListener("touchend", handleTouchEnd);
  };
}

// const removeSwipeListener = detectSwipe(
//   function(info, distance, position) {
//     console.log("滑动方向: ", info.direction);
//     console.log("滑动距离: ", distance);
//     console.log("当前手指位置: ", position);
//   },
//   function(info, distance, position) {
//     console.log("松开手时的滑动方向: ", info.direction);
//     console.log("松开手时的滑动距禿: ", distance);
//     console.log("当前手指位置: ", position);
//   },
//   { useObjectParam: true }
// );

// 调用返回的方法以移除监听
// removeSwipeListener();